import pytest

from gemini_antenna.URLHelper import URLHelper


@pytest.mark.blocklist_rules(
    "gemini://gemini.circumlunar.space",
    "https://",
)
def test_blocklist(url_helper: URLHelper):
    assert url_helper.isBlocked("gemini://gemini.circumlunar.space/news/atom.xml")
    assert url_helper.isBlocked("gemini.circumlunar.space/news/")
    assert url_helper.isBlocked("https://example.com/feed")
    assert not url_helper.isBlocked("gopher://gemini.circumlunar.space/")
    assert not url_helper.isBlocked("gemini://example.com/feed")
    assert not url_helper.isBlocked("")

    with pytest.raises(TypeError):
        url_helper.isBlocked(None)


def test_url_validation():
    assert URLHelper.mightBeAURL("https://😀.com")
    assert not URLHelper.mightBeAURL("gopher://")
    assert not URLHelper.mightBeAURL("gemini://.gmi")
    assert not URLHelper.mightBeAURL("//example.com/feed")
    assert not URLHelper.mightBeAURL("example.com/feed")
    assert not URLHelper.mightBeAURL("/etc/passwd")
    assert not URLHelper.mightBeAURL("mailto:example@example.com")

    with pytest.raises(TypeError):
        URLHelper.mightBeAURL(None)
    with pytest.raises(TypeError):
        URLHelper.mightBeAURL(123)
    with pytest.raises(TypeError):
        URLHelper.mightBeAURL(["gemini://example.com"])


def test_url_correction():
    correctURLs = (
        "gemini://gemini.circumlunar.space/news/atom.xml",
        "GEMINI://example.com",
        "https://😀.com"
    )
    for url in correctURLs:
        assert URLHelper.correct(url) == url

    assert(URLHelper.correct("https%3A//example.com/feed%3Fformat%3Datom")
           == "https://example.com/feed?format=atom")
    assert(URLHelper.correct("example.com/my-feed")
           == "gemini://example.com/my-feed")


def test_url_resolving():
    canonicalURLs = (
        "gemini://gemini.circumlunar.space/news/atom.xml",
        "gemini://gemini.circumlunar.space/news/"
    )
    for url in canonicalURLs:
        assert URLHelper.resolve(url) == url

    assert URLHelper.resolve("GEMINI://example.com") == "gemini://example.com"
    assert(URLHelper.resolve("gemini://example.com/../../..")
           == "gemini://example.com/")
    assert(URLHelper.resolve("gemini://example.org/feed/.")
           == "gemini://example.org/feed")
    assert(URLHelper.resolve("gemini://example.org/feed/./feed2")
           == "gemini://example.org/feed/feed2")
    assert(URLHelper.resolve("gemini://example.org/feed/./../feed2")
           == "gemini://example.org/feed2")
